package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.domain.StrategyCatalog;
import cn.wolfcode.wolf2w.query.StrategyCatalogQuery;
import cn.wolfcode.wolf2w.repository.StrategyCatalogRepository;
import cn.wolfcode.wolf2w.repository.StrategyRepository;
import cn.wolfcode.wolf2w.service.IDestinationService;
import cn.wolfcode.wolf2w.service.IStrategyCatalogService;
import cn.wolfcode.wolf2w.vo.CotalogVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class StrategyCatalogServiceImpl implements IStrategyCatalogService {

    @Autowired
    private MongoTemplate template;
    @Autowired
    private StrategyCatalogRepository repository;
    @Autowired
    private IDestinationService destinationService;
    @Autowired
    private StrategyRepository strategyRepository ;

    @Override
    public void save(StrategyCatalog strategyCatalog) {
        strategyCatalog.setId(null);
        repository.save(strategyCatalog);
    }

    @Override
    public void update(StrategyCatalog strategyCatalog) {
        repository.save(strategyCatalog);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public StrategyCatalog get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<StrategyCatalog> list() {
        return repository.findAll();
    }

    @Override
    public Page<StrategyCatalog> query(StrategyCatalogQuery qo) {
        Query query = new Query();
        long count = template.count(query, StrategyCatalog.class);
        if (count == 0) {
            Page.empty();
        }
        if (count % qo.getPageSize() == 0 && qo.getCurrentPage() > 1) {
            qo.setCurrentPage(qo.getCurrentPage() - 1);
        }
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        query.with(pageable);
        List<StrategyCatalog> StrategyCatalogs = template.find(query, StrategyCatalog.class);
        return new PageImpl<>(StrategyCatalogs, pageable, count);
    }

    @Override
    public void saveOrUpdate(StrategyCatalog strategyCatalog) {
        String destId = strategyCatalog.getDestId();
        Destination dest = destinationService.get(destId);
        strategyCatalog.setDestName(dest.getName());
        if (StringUtils.hasLength(strategyCatalog.getId())) {
            this.update(strategyCatalog);
        } else {
            this.save(strategyCatalog);
        }
    }

    @Override
    public List<CotalogVo> groupList() {
        List<CotalogVo> list = new ArrayList<>();
        TypedAggregation<StrategyCatalog> agg = Aggregation.newAggregation(StrategyCatalog.class,
                Aggregation.group("destName").
                        push("name").as("names").
                        push("id").as("ids")
        );
        AggregationResults<Map> result = template.aggregate(agg, Map.class);
        List<Map> datas = result.getMappedResults();
        for (Map data : datas) {
            CotalogVo vo = new CotalogVo();

            vo.setDestName(data.get("_id").toString());
            List<Map<String, Object>> mm = new ArrayList<>();
            List<Object> names = (List<Object>) data.get("names");
            List<Object> ids = (List<Object>) data.get("ids");
            for (int i = 0; i < names.size(); i++) {
                Map<String, Object> vv = new HashMap<>();
                String name = names.get(i).toString();
                String id = ids.get(i).toString();
                vv.put("id", id);
                vv.put("name", name);
                mm.add(vv);
            }
            vo.setCatalogList(mm);
            list.add(vo);
        }
        System.out.println(list);
        return list;
    }

    @Override
    public List<StrategyCatalog> queryCatalogByDestId(String destId) {

        List<StrategyCatalog> strategyCatalogs = repository.findByDestId(destId);

        for(StrategyCatalog catalog : strategyCatalogs){
            List<Strategy> strategies = strategyRepository.findByCatalogId(catalog.getId());
            catalog.setStrategies(strategies);
        }
        return strategyCatalogs;
    }
}